import { Context } from 'koa';
import config from '../config';
import { logger } from '../ins';
import axios from 'axios';
import { RSAUtils } from './rsaUtils';
import redisCluster from '../util/redisClient';
import { randomUUID } from 'crypto';
import { connectionPool } from '../init';

// 第三方跳转wps
export async function thirdToWps(ctx: Context) {
    logger.info(`======>thirdToWps,参数:${JSON.stringify(ctx.query)}`)
    const code = ctx.query.seeyonCode as string
    const yunHost = ctx.headers['x-origin'] as string
    redisCluster.set(`seeyonCode`, code)
    ctx.redirect(yunHost)
    return
}

//对url中的参数进行私钥解密   
export async function encryptByPrivateKey(oop: string) {
    const privateKey = `${config.oauth.privateKey}`;
    const encryptedLogin = Buffer.from(oop, "base64");
    logger.info("解密前encryptedLogin", encryptedLogin);
    // 使用私钥解密
    const decryptLogin = await RSAUtils.decryptByPublicKey(
        encryptedLogin,
        privateKey
    );
    const decryptLoginStr = decryptLogin.toString();
    logger.info("解密后原始字符串:", decryptLoginStr);

    // 将 JSON 字符串解析为对象
    const parsedData = JSON.parse(decryptLoginStr);

    // 提取三个参数
    const decryptLoginType: string = parsedData.type;
    const decryptLoginAccount: string = parsedData.account;
    const decryptLoginPassword: string = parsedData.password;

    logger.info("解密后account", decryptLoginAccount);
    logger.info("解密后type", decryptLoginType);
    logger.info("解密后password", decryptLoginPassword);

    return { decryptLoginAccount, decryptLoginType, decryptLoginPassword };
}

//对密码进行base6加密
function base64Encrypt(password: string): string {
    const combined = "seeyon" + password;
    // 使用 Buffer 编码
    const encoded = Buffer.from(combined).toString("base64");
    return encoded;
}

//验证账号和密码
export async function verifyAccountandPassword(ctx: Context) {
    const uuid = randomUUID();
    let rsp = await encryptByPrivateKey(ctx.query.oop as string);
    const header = {
        'Content-Type': 'application/json;charset=utf8'
    };
    const type = rsp.decryptLoginType;
    try {
        if (type == "1") {
            logger.info(`=============>账号密码登录:${type}`)
            const encryptPassword = base64Encrypt(rsp.decryptLoginPassword)
            logger.info(`=============>加密后的密码为:${encryptPassword}`)
            const body = {
                "type": type,
                "account": rsp.decryptLoginAccount,
                "password": encryptPassword

            }
            const verifyrsp = await axios.post(config.oauth.verify, body, { headers: header })
            if (verifyrsp.data.success) {
                logger.info(`=============>账号密码验证成功:${type}`)
                //        redisCluster.set(uuid, `account_${rsp.decryptLoginAccount}`)
                ctx.body = {
                    msg: true,
                    uid: verifyrsp.data.uid
                }
                return ctx
            }
            ctx.body = {
                msg: false,
            }
            return ctx
        }
        if (type == "2") {
            logger.info(`=============>手机号密码登录:${type}`)
            const encryptPassword = base64Encrypt(rsp.decryptLoginPassword)
            logger.info(`=============>加密后的密码为:${encryptPassword}`)
            const body = {
                "type": type,
                "account": rsp.decryptLoginAccount,
                "password": encryptPassword

            }
            const verifyrsp = await axios.post(config.oauth.verify, body, { headers: header })
            if (verifyrsp.data.success) {
                logger.info(`=============>手机号密码验证成功:${type}`)
                //     redisCluster.set(uuid, `phone_${rsp.decryptLoginAccount}`)
                ctx.body = {
                    msg: true,
                    uuid: verifyrsp.data.uid
                }
                return ctx
            }
            ctx.body = {
                msg: false,
            }
            return ctx
        }
    } catch (e) {
        logger.error(`=============>验证失败，用户名或密码无效:${type}`)
    }

}

export async function redirectWps(ctx: Context) {
    logger.info(`======>redirectWps,参数:${JSON.stringify(ctx.query)}`)
    const redirect_uri = ctx.query.redirect_uri as string;
    const state = ctx.query.state as string;
    const yunHost = ctx.headers['x-origin'] as string
    const code = ctx.query.code as string;
    const originSeeyonCode = await redisCluster.get('seeyonCode');
    let url = ''
    if (originSeeyonCode) {
        logger.info(`======>OA免密登录:${originSeeyonCode}`)
        const seeyonCode = `OA_${originSeeyonCode}`;
        url = `${redirect_uri}&code=${seeyonCode}&state=${state}`
        logger.info("=======>二次redirectWps,url:", url)
        ctx.status = 302
        ctx.redirect(url)
        return
    }
    url = `${config.oauth.loginUrl}?redirect_uri=${encodeURIComponent(redirect_uri)}&state=${state}`
    logger.info("=======跳转到登录界面:", url)
    ctx.status = 302
    ctx.redirect(url)
    return
}

export async function callBack(ctx: Context) {
    try {
        const code = ctx.query.code as string;
        logger.info(`======>callBack参数:${JSON.stringify(ctx.query)}`)
        if (code.includes('OA_')) {
            logger.info(`======>OA免密登录:${code}`)
            ctx.status = 200
            ctx.body = {
                access_token: code,
            }
            return ctx
        }
        ctx.status = 200
        ctx.body = {
            access_token: code,
        }
        return ctx
    } catch (error) {
        logger.error(error)
        return
    }
}


export async function userInfo(ctx: Context) {
    try {
        logger.info(`======>userInfo参数:${JSON.stringify(ctx.query)}`)
        let token = ctx.query.access_token as string
        if (token.includes('OA_')) {
            token = token.replace('OA_', '')
            logger.info(`======>OA免密登录:${token}`)
            const response = await axios.get(`${config.oauth.userInfoUrl}?seeyonCode=${token}`);
            let uid = response.data.data.id
            logger.info("获取到的userId", { data: uid })
            // 返回格式
            ctx.status = 200
            ctx.body = {
                union_id: uid
            }
            return ctx
        }
        // const acc = await redisCluster.get(token)
        // if (acc.includes(`account_`)) {
        //     const account = acc.replace('account_', '')
        //     logger.info(`======>账号登录:${account}`)
        //     const uid = await getUserIdbyacc(account)
        //     logger.info("获取到的userId", { data: uid })
        //     ctx.status = 200
        //     ctx.body = {
        //         union_id: uid
        //     }
        //     return ctx
        // }
        // if (acc.includes(`phone_`)) {
        //     const phone = acc.replace('phone_', '')
        //     logger.info(`======>手机号登录:${phone}`)

        //     const uid = await getUserIdbypho(phone)
        //     logger.info("获取到的userId", { data: uid })
        //     ctx.status = 200
        //     ctx.body = {
        //         union_id: uid
        //     }
        //     return ctx
        // }
        ctx.status = 200
        ctx.body = {
            union_id: `${token}`
        }
        return ctx
    } catch (e) {
        logger.info(e)
        ctx.status = 200
        ctx.body = {
            msg: e || '系统开小差了！',
            result: '9999'
        }
        return
    }
}

// async function getUserIdbyacc(account: string) {
//     const [rows] = await connectionPool.execute(
//         'SELECT uid FROM tb_las_user WHERE account = ?',
//         [account]
//     );
//     if (rows.length === 0) {
//         logger.info(`用户不存在：${account}`);
//     } else {
//         const uid = rows[0];
//         return uid;
//     }
// }


// async function getUserIdbypho(phone: string) {
//     const [rows] = await connectionPool.execute(
//         'SELECT uid FROM tb_las_user WHERE phone = ?',
//         [phone]
//     );
//     if (rows.length === 0) {
//         logger.info(`用户不存在：${phone}`);
//     } else {
//         const uid = rows[0];
//         return uid;
//     }
// }
